﻿using IceInk;
using IceInkCapsLodkTip.Scripts;
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace IceInkCapsLodkTip
{

    public partial class MainForm : Form
    {
        // 系统托盘图标组件
        private NotifyIcon trayIcon;

        // 图标资源（内置默认图标）
        private Icon iconCapsOn;
        private Icon iconCapsOff;

        // 键盘状态检测
        private Timer statusCheckTimer;

        /// <summary>
        /// 上次大小写键盘是否开启
        /// </summary>
        private bool lastCapsState;

        /// <summary>
        /// 上次数字键盘是否开启
        /// </summary>
        private bool lastNumLockState;


        /// <summary>
        /// 开机启动菜单按钮
        /// </summary>
        private MenuItem startupMenuItem;

        /// <summary>
        /// 退出程序菜单按钮
        /// </summary>
        MenuItem exitMenuItem;

        public MainForm()
        {
            InitializeComponent();
            InitializeApplication();
        }

        private void InitializeApplication()
        {
            // 创建内置图标
            CreateIcons();

            // 设置系统托盘图标
            trayIcon = new NotifyIcon
            {
                Icon = Control.IsKeyLocked(Keys.CapsLock) ? iconCapsOn : iconCapsOff,
                Text = "大小写状态指示器",
                Visible = true
            };

            //开机启动菜单
            startupMenuItem = new MenuItem("开机启动", ToggleStartup);
            startupMenuItem.Checked = StartupManager.IsStartupEnabled();

            //退出程序按钮
            exitMenuItem = new MenuItem("退出", (s, e) => ExitCleanupResources());

            //右键菜单列表
            trayIcon.ContextMenu = new ContextMenu(new[]
            {
                startupMenuItem,
                new MenuItem("-"),
                exitMenuItem
            });

            // 初始化状态检测计时器
            statusCheckTimer = new Timer { Interval = 100 };
            statusCheckTimer.Tick += CheckCapsLockStatus;
            statusCheckTimer.Start();

            // 保存初始状态
            lastCapsState = Control.IsKeyLocked(Keys.CapsLock);
        }

        private void CreateIcons()
        {
            // 获取程序集引用

            string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
            string cOn = Path.Combine(baseDirectory, "Resources", "CapsOn.ico");
            string cOff = Path.Combine(baseDirectory, "Resources", "CapsOff.ico");

            // 从嵌入资源加载图标
            try
            {
                if (File.Exists(cOn))
                    iconCapsOn = new Icon(cOn);
                if (File.Exists(cOff))
                    iconCapsOff = new Icon(cOff);

                //using (var streamOn = File.OpenRead(cOn))
                //{
                //    using (var streamOff = File.OpenRead(cOff))
                //    {
                //        if (streamOn != null)
                //            iconCapsOn = new Icon(streamOn);
                //        if (streamOff != null)
                //            iconCapsOff = new Icon(streamOff);
                //    }
                //}
            }
            catch
            {

            }

            // 如果加载失败创建默认图标
            if (iconCapsOn == null) iconCapsOn = CreateDefaultIcon(Color.DeepSkyBlue, true);//DarkSeaGreen
            if (iconCapsOff == null) iconCapsOff = CreateDefaultIcon(Color.DeepPink, false);
        }

        // 创建默认图标（备用）
        private Icon CreateDefaultIcon(Color color, bool isOn)
        {
            using (var bmp = new Bitmap(32, 32))
            {
                using (var g = Graphics.FromImage(bmp))
                {
                    using (var font = new Font("楷体", 30, FontStyle.Bold))
                    {
                        g.Clear(Color.Transparent);
                        if (isOn)
                            g.DrawString("A", font, new SolidBrush(color), new PointF(0, 0));
                        else
                            g.DrawString("a", font, new SolidBrush(color), new PointF(0, 0));
                        return Icon.FromHandle(bmp.GetHicon());
                    }
                }

            }
        }

        /// <summary>
        /// 大小写切换状态改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CheckCapsLockStatus(object sender, EventArgs e)
        {
            bool currentState = Control.IsKeyLocked(Keys.CapsLock);//大小写键盘监听
            bool numLockState = Control.IsKeyLocked(Keys.NumLock);//数字键盘监听

            //if (currentState != lastCapsState || numLockState != lastNumLockState)
            //{
            //    string str = string.Empty;

            //    if (currentState)//大写
            //        str = "大写键盘!";
            //    else
            //        str = "小写键盘!";


            //    if (numLockState)
            //        str += "(开启)数字键盘";
            //    else
            //        str += "(关闭)数字键盘";


            //    this.TipOk(null, str);
            //}


            //大小写键盘监听
            if (currentState != lastCapsState)
            {
                trayIcon.Icon = currentState ? iconCapsOn : iconCapsOff;
                trayIcon.Text = currentState ? "大写锁定已开启" : "大写锁定已关闭";
                lastCapsState = currentState;

                if (currentState)//大写
                    this.TipOk(null, "大写键盘");
                else
                    this.TipWarning(null, "小写键盘");
            }

            //数字键盘是否开启
            if (numLockState != lastNumLockState)
            {
                lastNumLockState = numLockState;

                if (numLockState)
                    this.TipOk(null, "(开启)数字键盘");
                else
                    this.TipWarning(null, "(关闭)数字键盘");
            }



        }

        protected override void OnLoad(EventArgs e)
        {
            // 隐藏主窗口
            Visible = false;
            ShowInTaskbar = false;
            base.OnLoad(e);
        }

        /// <summary>
        /// 检查开机启动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ToggleStartup(object sender, EventArgs e)
        {
            bool newState = !StartupManager.IsStartupEnabled();
            if (StartupManager.ToggleStartup(newState))
            {
                startupMenuItem.Checked = newState;
                // startupMenuItem.Text = newState ? "开机启动" : "开机启动";
            }
            else
            {
                MessageBox.Show("无法修改启动项设置，请检查注册表权限。", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 资源清理 推出程序
        /// </summary>
        private void ExitCleanupResources()
        {
            // 销毁图标句柄
            if (iconCapsOn != null)
            {
                DestroyIcon(iconCapsOn.Handle);
                iconCapsOn.Dispose();
            }
            if (iconCapsOff != null)
            {
                DestroyIcon(iconCapsOff.Handle);
                iconCapsOff.Dispose();
            }

            // 移除托盘图标
            trayIcon?.Dispose();


            Application.Exit();
        }

        // 导入系统API销毁图标
        [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
        private static extern bool DestroyIcon(IntPtr handle);

    }

}


